#include "TriangleP.h"

TriangleP::TriangleP(float x1,float x2, float x3, float y1, float y2, float y3, float z1, float z2, float z3, Material *mat,Texture *tex):Primitive(mat,tex){
	this->x1=x1;
	this->x2=x2;
	this->x3=x3;
	this->y1=y1;
	this->y2=y2;
	this->y3=y3;
	this->z1=z1;
	this->z2=z2;
	this->z3=z3;

	float ux = x2 -x1;
	float uy = y2 -y1;
	float uz = z2 -z1;

	float vx = x3 -x1;
	float vy = y3 -y1;
	float vz = z3 -z1;

	nx = uy*vz - uz*vy;
	ny = uz*vx - ux*vz;
	nz = ux*vy - uy*vx;
}

void TriangleP::act(float texLS, float texLT){
	
	getMat()->act();
	getTex()->act();


	float ls,lt;
	if(tex->inheritTex){
		ls=texLS;
		lt=texLT;
	}
	else{
		ls=getTex()->getLengthS();
		lt=getTex()->getLengthT();
	}

	float acN= sqrt( (x3-x1)*(x3-x1) + (y3-y1)*(y3-y1) + (z3-z1)*(z3-z1));
	float abN= sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1));

	float ab[3],ac[3];
	ab[0]=(x2-x1)/abN;
	ab[1]=(y2-y1)/abN;
	ab[2]=(z2-z1)/abN;
	ac[0]=(x3-x1)/acN;
	ac[1]=(y3-y1)/acN;
	ac[2]=(z3-z1)/acN;
	
	float cosAlfa =abs(ab[0]*ac[0]+ab[1]*ac[1]+ab[2]*ac[2]);
	float AD = abN*cosAlfa;
	float AE = abN*sin(acos(cosAlfa));

	glBegin(GL_POLYGON);
		glNormal3d(nx,ny, nz);
	 	glTexCoord2f(acN/ls, 0.0);
		glVertex3f(x1, y1, z1);
		glTexCoord2f(AD/ls,AE/lt);
		glVertex3f(x2, y2, z2);	
		glTexCoord2f(0.0, 0.0);
		glVertex3f(x3, y3, z3);
	glEnd();

}